package com.ruoyi.web.controller.module.estate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.*;
import com.ruoyi.system.domain.module.event.EventTerminalGroup;
import com.ruoyi.system.domain.module.property.PropertyFeeOrderTemplate;
import com.ruoyi.system.service.module.estate.*;
import com.ruoyi.system.service.module.property.IPropertyFeeOrderOfflineInfoService;
import com.ruoyi.system.service.module.property.IPropertyFeeOrderTemplateService;
import com.ruoyi.system.service.module.property.IPropertyService;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 楼栋（1级） + 单元（2级） Controller
 *
 * @author ruoyi
 * @date 2023-12-31
 */
@Validated
@Api(value = "楼栋（1级） + 单元（2级） 控制器", tags = {"楼栋（1级） + 单元（2级） 管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/estate/build")
public class EstateBuildController extends BaseController {

    private final IEstateBuildService estateBuildService;
	private final IEstateService estateService;
	private final IEstateRoomService estateRoomService;
	private final IPropertyService propertyService;
	private final IEstateBuildFloorService estateBuildFloorService;
	private final IEstateBuildUnitService estateBuildUnitService;
	private final IEstateRoomBangUserService estateRoomBangUserService;
	private final IPropertyFeeOrderTemplateService propertyFeeOrderTemplateService;

    /**
     * 查询楼栋（1级） + 单元（2级） 列表
     */
    @ApiOperation("查询楼栋（1级） + 单元（2级） 列表")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:list')")
    @GetMapping("/list")
    public EstateBuildTree list(@Validated EstateBuild estateBuild) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateBuild> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if (estateBuild.getPropertyId()!=null){
				qw.eq("property_id",estateBuild.getPropertyId());
			}
			if (estateBuild.getEstateId()!=null){
				qw.eq("estate_id",estateBuild.getEstateId());
			}
		}
		if (estateBuild.getId()!=null){
			qw.eq("id",estateBuild.getId());
		}
//		if (estateBuild.getParentId()!=null){
//			qw.eq("parent_id",estateBuild.getParentId());
//		}
        List<EstateBuild> list = estateBuildService.list(qw);
		//添加楼
		EstateBuildTree tree = new EstateBuildTree();
		if(list.size()>0){
			EstateBuild list1=list.get(0);
			if (list1.getEstateId()!=null){
				tree.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
			if (list1.getBuildName()!=null){
				tree.setBuildName(list1.getBuildName());
			}
			if (list1.getId()!=null){
				tree.setId(list1.getId());
				//添加单元
				List<EstateUnitTree> unitTrees = new ArrayList<>();
				QueryWrapper<EstateBuildUnit> qwUnit = new QueryWrapper<>();
				qwUnit.eq("build_id",list1.getId());
				qwUnit.orderByAsc("sort");
				List<EstateBuildUnit> unitList = estateBuildUnitService.list(qwUnit);
				for (EstateBuildUnit unit : unitList){
					EstateUnitTree unitTree = new EstateUnitTree();
					if (unit.getUnitNo()!=null){
						unitTree.setUnitNo(unit.getUnitNo());
					}
					if (unit.getId()!=null){
						unitTree.setId(unit.getId());
						//添加楼层
						List<EstateFloorTree> floorTrees = new ArrayList<>();
						QueryWrapper<EstateBuildFloor> qwFloor = new QueryWrapper<>();
						qwFloor.eq("unit_id",unit.getId());
						qwFloor.orderByDesc("sort");
						List<EstateBuildFloor> floorList = estateBuildFloorService.list(qwFloor);
						if (floorList.size()>0){
							for (EstateBuildFloor floor : floorList){
								EstateFloorTree floorTree = new EstateFloorTree();
								if (floor.getFloorName()!=null){
									floorTree.setFloorName(floor.getFloorName());
								}
								if (floor.getId()!=null){
									floorTree.setId(floor.getId());
									//添加户
									List<EstateRoomTree> roomTrees = new ArrayList<>();
									QueryWrapper<EstateRoom> qwRoom = new QueryWrapper<>();
									qwRoom.eq("floor_id",floor.getId());
									qwRoom.orderByAsc("room_num");
									List<EstateRoom> roomList = estateRoomService.list(qwRoom);
									unitTree.setSize(roomList.size());
									if (roomList.size()>0){
										for (EstateRoom room : roomList){
											EstateRoomTree roomTree = new EstateRoomTree();
											if (room.getRoomNo()!=null){
												roomTree.setRoomNo(room.getRoomNo());
											}
											if (room.getRealName()!=null){
												roomTree.setRealName(room.getRealName());
											}
											if (room.getPhoneNum()!=null){
												roomTree.setPhoneNum(room.getPhoneNum());
											}
											if (room.getState()!=null){
												roomTree.setState(room.getState());
											}
											if (room.getId()!=null){
												roomTree.setId(room.getId());
											}
											if (room.getVacantEndDate()!=null){
												Date date = new Date();
												if (room.getVacantBeginDate().getTime()<date.getTime()&&room.getVacantEndDate().getTime()>date.getTime()){
													roomTree.setKongzhi(1);
												}else {
													roomTree.setKongzhi(0);
												}
											}
											if (room.getRealName()!=null){
												int p = 0;
												int n = 0;
												QueryWrapper<PropertyFeeOrderTemplate> qwFee = new QueryWrapper<>();
												qwFee.eq("room_id",room.getId());
												qwFee.eq("fee_type","wyf");
												List<PropertyFeeOrderTemplate> feeList = propertyFeeOrderTemplateService.list(qwFee);
												if (feeList.size()>0){
													for (PropertyFeeOrderTemplate fee:feeList){
														if (fee.getState()!=0){
															p = Integer.parseInt(fee.getMonthNum());
															n = Integer.parseInt(fee.getYearNum());
															continue;
														}
													}
												}
 												roomTree.setQianfei(p);
												roomTree.setNianfen(n);
											}
											if (room.getRealName()!=null){
												int p = 0;
												QueryWrapper<EstateRoomBangUser> qwRooms = new QueryWrapper<>();
												qwRooms.eq("room_id",room.getId());
												List<EstateRoomBangUser> user = estateRoomBangUserService.list(qwRooms);
												if (user.size()>0){
													p = 1;
												}
												roomTree.setBangWxUser(p);
											}
											roomTrees.add(roomTree);
										}
										floorTree.setEstateRoomTrees(roomTrees);
									}
								}
								floorTrees.add(floorTree);
							}
							unitTree.setEstateFloorTrees(floorTrees);
						}
					}
					unitTrees.add(unitTree);
				}
				tree.setEstateUnitTree(unitTrees);
			}
		}
		return tree;
    }


	@ApiOperation("查询楼栋（1级） + 单元（2级） 列表")
	@PreAuthorize("@ss.hasPermi('module:estateBuild:list')")
	@GetMapping("/buildNum")
	public Integer buildNum(@Validated EstateBuild estateBuild) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateBuild> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if (sysUser.getUserType() == 2) {
			qw.eq("property_id", sysUser.getPropertyId());
		} else if (sysUser.getUserType() == 3) {
			qw.eq("estate_id", sysUser.getEstateId());
		} else if (sysUser.getUserType()==0){
			return 2125;
		}else {
			if (estateBuild.getPropertyId() != null) {
				qw.eq("property_id", estateBuild.getPropertyId());
			}
			if (estateBuild.getEstateId() != null) {
				qw.eq("estate_id", estateBuild.getEstateId());
			}
		}
		if (estateBuild.getId() != null) {
			qw.eq("id", estateBuild.getId());
		}
		List<EstateBuild> estateBuilds = estateBuildService.list(qw);
		return estateBuilds.size();
	}
	/**
	 * 查询楼栋的 楼层数据列表
	 */
	@ApiOperation("查询楼栋的 楼层数据列表")
	@PreAuthorize("@ss.hasPermi('module:estateFloor:list')")
	@GetMapping("/listBuild")
	public List<EstateBuild> listBuild(@Validated EstateBuild estateBuild) {
		SysUser sysUser = getUser();
		QueryWrapper<EstateBuild> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if (estateBuild.getPropertyId()!=null){
				qw.eq("property_id",estateBuild.getPropertyId());
			}
			if (estateBuild.getEstateId()!=null){
				qw.eq("estate_id",estateBuild.getEstateId());
			}
		}
		if (estateBuild.getId()!=null){
			qw.eq("id",estateBuild.getId());
		}
		qw.orderByAsc("sort");
		List<EstateBuild> td = estateBuildService.list(qw);
		List<EstateBuild> buildList = new ArrayList<>();
		if(td.size()>0){
			for (EstateBuild build:td){
				QueryWrapper<EstateBuildUnit> qw1 = new QueryWrapper<>();
				qw1.eq("build_id", build.getId());
				qw1.orderByAsc("sort");
				List<EstateBuildUnit> units = estateBuildUnitService.list(qw1);
				for (EstateBuildUnit unit :units){
					EstateBuild build1 = new EstateBuild();
					build1.setBuildName(unit.getUnitNo());
					build1.setId(unit.getId());
					build1.setParentId(unit.getBuildId()+100000);
					build1.setBuildType(0);
					build1.setLevel(2);
					build1.setBuildNo(unit.getUnitNo());
					buildList.add(build1);
				}
				build.setId(build.getId()+100000);
			}
		}
		for (EstateBuild build:buildList){
			td.add(build);
		}

		return td;
	}


	/**
	 * 查询楼栋（1级） + 单元（2级） 列表
	 */
	@ApiOperation("查询楼栋（1级） + 单元（2级） 列表")
	@PreAuthorize("@ss.hasPermi('module:estateBuild:list')")
	@GetMapping("/buildListAll")
	public List<EstateBuild> buildListAll(@Validated EstateBuild estateBuild) {
		QueryWrapper<EstateBuild> qw = new QueryWrapper<>();
		if (estateBuild.getEstateId() != null) {
			qw.eq("estate_id",estateBuild.getEstateId());
		}
		qw.orderByAsc("sort");
		List<EstateBuild> list = estateBuildService.list(qw);
		return list;
	}

		/**
		 * 查询楼栋（1级） + 单元（2级） 列表
		 */
	@ApiOperation("批量添加楼宇")
	@PreAuthorize("@ss.hasPermi('module:estateBuild:list')")
	@GetMapping("/addAllRoom")
	public TableDataInfo<EstateBuild> addAllRoom(@Validated EstateBuild estateBuild) {
		Estate estate = estateService.findById(estateBuild.getEstateId());
		//删除原有记录
		QueryWrapper<EstateBuild> qwBuild = new QueryWrapper<>();
		qwBuild.eq("estate_id",estateBuild.getEstateId());
		List<EstateBuild> estateBuildList = estateBuildService.list(qwBuild);
		for (EstateBuild build:estateBuildList){
			QueryWrapper<EstateBuildUnit> qwUnit = new QueryWrapper<>();
			qwUnit.eq("build_id",build.getId());
			List<EstateBuildUnit> units = estateBuildUnitService.list(qwUnit);
			for (EstateBuildUnit unit:units){
				estateBuildUnitService.removeById(unit.getId());
			}
			QueryWrapper<EstateBuildFloor> qwFloor = new QueryWrapper<>();
			qwFloor.eq("build_id",build.getId());
			List<EstateBuildFloor> floors = estateBuildFloorService.list(qwFloor);
			for (EstateBuildFloor floor:floors){
				estateBuildFloorService.removeById(floor.getId());
			}
			estateBuildService.removeById(build.getId());
		}
		//录入楼宇表
		List<EstateBuild> estateBuilds = estateRoomService.getEstateBuildList(estateBuild.getEstateId(),estate.getPropertyId());
		if (estateBuilds.size()>0){
			for (EstateBuild build :estateBuilds){
				estateBuildService.save(build);
				//录入单元表
				List<EstateBuildUnit> estateBuildUnits = estateRoomService.getEstateBuildUnitList(build.getBuildNo(),build.getId(),estateBuild.getEstateId());
				for (EstateBuildUnit unit : estateBuildUnits){
					estateBuildUnitService.save(unit);
					//录入楼层表
					List<EstateBuildFloor> estateBuildFloor = estateRoomService.getEstateBuildFloorList(build.getBuildNo(),unit.getUnitNo(),build.getId(),unit.getId(),estateBuild.getEstateId(),estate.getPropertyId());
					for (EstateBuildFloor floor:estateBuildFloor){
						estateBuildFloorService.save(floor);
						//绑定房屋
						QueryWrapper<EstateRoom> qw = new QueryWrapper<>();
						qw.eq("build_no",build.getBuildNo());
						qw.eq("unit_no",unit.getUnitNo());
						qw.eq("estate_id",estateBuild.getEstateId());
						List<EstateRoom> roomList = estateRoomService.list(qw);
						for (EstateRoom room : roomList){
							room.setBuildId(build.getId());
							room.setUnitId(unit.getId());
							if (room.getRoomNum().length()==3){
								if (floor.getFloorNum().equals(room.getRoomNum().substring(0,1))){
									room.setFloorId(floor.getId());
								};
							}else if (room.getRoomNum().length()==4){
								if (floor.getFloorNum().equals(room.getRoomNum().substring(0,2))){
									room.setFloorId(floor.getId());
								};
							};
							estateRoomService.updateById(room);
						}
					}
				}
			}
		}


		return null;
	}

	/**
	 * 查询楼栋（1级） + 单元（2级） 列表
	 */
	@ApiOperation("查询楼栋（1级） + 单元（2级） 列表")
	@PreAuthorize("@ss.hasPermi('module:estateBuild:list')")
	@GetMapping("/getTreeSelect")
	public AjaxResult getTreeSelect(@Validated EstateBuild estateBuild) {
		List<EstateBuild> list = estateBuildService.getTreeSelect(estateBuild.getEstateId());
		return AjaxResult.success(list);
	}


	/**
     * 导出楼栋（1级） + 单元（2级） 列表
     */
    @ApiOperation("导出楼栋（1级） + 单元（2级） 列表")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:export')")
    @Log(title = "楼栋（1级） + 单元（2级） ", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EstateBuild> export(@Validated EstateBuild estateBuild) {
        List<EstateBuild> list = estateBuildService.list();
        ExcelUtil<EstateBuild> util = new ExcelUtil<EstateBuild>(EstateBuild.class);
        return util.exportExcel(list, "楼栋（1级） + 单元（2级） ");
    }

    /**
     * 获取楼栋（1级） + 单元（2级） 详细信息
     */
    @ApiOperation("获取楼栋（1级） + 单元（2级） 详细信息")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:query')")
    @GetMapping("/{id}")
    public AjaxResult<EstateBuild> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateBuild estateBuild = estateBuildService.getById(id);
        return AjaxResult.success(estateBuild);
    }

    /**
     * 新增楼栋（1级） + 单元（2级）
     */
    @ApiOperation("新增楼栋（1级） + 单元（2级） ")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:add')")
    @Log(title = "楼栋（1级） + 单元（2级） ", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateBuild estateBuild) {
		if (estateBuild.getPropertyId()==null){
			if (estateBuild.getEstateId()!=null){
				Estate estate = estateService.findById(estateBuild.getEstateId());
				if (estate!=null){
					estateBuild.setPropertyId(estate.getPropertyId());
				}
			}
		}
//		if (estateBuild.getPropertyId()==0){
//			estateBuild.setLevel(1);
//		}else {
//			estateBuild.setLevel(2);
//		}

		boolean bl = estateBuildService.save(estateBuild);
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 修改楼栋（1级） + 单元（2级）
     */
    @ApiOperation("修改楼栋（1级） + 单元（2级） ")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:edit')")
    @Log(title = "楼栋（1级） + 单元（2级） ", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateBuild estateBuild) {
		if (estateBuild.getPropertyId()==null){
			if (estateBuild.getEstateId()!=null){
				Estate estate = estateService.findById(estateBuild.getEstateId());
				if (estate!=null){
					estateBuild.setPropertyId(estate.getPropertyId());
				}
			}
		}
        return toAjax(estateBuildService.updateById(estateBuild) ? 1 : 0);
    }

    /**
     * 删除楼栋（1级） + 单元（2级）
     */
    @ApiOperation("删除楼栋（1级） + 单元（2级） ")
    @PreAuthorize("@ss.hasPermi('module:estateBuild:remove')")
    @Log(title = "楼栋（1级） + 单元（2级） " , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
		for (Long id : ids){
			//删除子集
			QueryWrapper<EstateBuild> qw1 = new QueryWrapper<>();
			qw1.eq("parent_id",id);
			List<EstateBuild> estateBuilds = estateBuildService.list(qw1);
			for (EstateBuild list2 : estateBuilds){
				//删除绑定楼层
				QueryWrapper<EstateBuildFloor> qw = new QueryWrapper<>();
				qw.eq("build_id",list2.getId());
				List<EstateBuildFloor> list = estateBuildFloorService.list(qw);
				for (EstateBuildFloor list1:list){
					estateBuildFloorService.removeById(list1.getId());
				}
				estateBuildService.removeById(list2.getId());
			}
			//删除自身绑定楼层
			QueryWrapper<EstateBuildFloor> qw = new QueryWrapper<>();
			qw.eq("build_id",id);
			List<EstateBuildFloor> list = estateBuildFloorService.list(qw);
			for (EstateBuildFloor list1:list){
				estateBuildFloorService.removeById(list1.getId());
			}
		}
        return toAjax(estateBuildService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
